import React, {FC, useContext, useEffect, useState} from 'react';
import "./index.less";
import {Divider, QRCode} from 'antd';
import * as API from "@/services";
import * as numeral from "numeral";
import {DEFAULT_WS_TOPICS, KfModal, useBackendEnum, useStompSubscription} from "kf-web-library";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import {useCountDown, useDebounceFn, useRafInterval, useRequest, useThrottleFn} from "ahooks";
import dayjs, {Dayjs} from "dayjs";
import {MallOrderContext} from "@/pages/MallPage/MallOrder/MallOrderContext";
import {queryFrontPayRecord} from "@/services";
import {FormattedMessage} from "umi";

interface MallOrderPendingPayinfoProps {
  pendingPayInfo: API.JournalSubscribe_Response;
}

const MallOrderPendingPayinfo: FC<MallOrderPendingPayinfoProps> = (props) => {
  const {pendingPayInfo} = props;
  const {isZhCN} = useContext(HxConfigContext)
  const {enumDict, enumTypeDict, getBackendEnum} = useBackendEnum();
  const {onPaymentSuccess} = useContext(MallOrderContext);

  const [limlitPaymentTime, setLimlitPaymentTime] = useState<Dayjs | undefined>();
  const [limlitPaymentTimeCountdown] = useCountDown({targetDate: limlitPaymentTime});

  useEffect(() => {
    setLimlitPaymentTime(dayjs().add(pendingPayInfo.expirationSecond, "second"))
  }, []);

  //防抖,5秒内只能触发一次,除了第一次后面的丢弃,
  //避免轮询查询支付状态 和 Websockt同时收到支付成功后, onPaymentSuccess被触发多次
  const {run: onDebouncePaymentSuccess} = useDebounceFn(
    (orderNo: string) => {
      onPaymentSuccess?.(orderNo);
    },
    {
      leading: true,
      trailing: false,
      wait: 5000,
    },
  );

  const {
    run: runRefreshPayRecord,
    cancel: cancelRefreshPayRecord
  } = useRequest(() => API.queryFrontPayRecord(pendingPayInfo.orderNo), {
    pollingInterval: 5000, //5秒轮询一次
    pollingWhenHidden: false,
    manual: true,   //手动启动轮询
    onSuccess: (res) => {
      if (res.data.paymentStatus === "SUCCESS") {
        cancelRefreshPayRecord();
        onDebouncePaymentSuccess(pendingPayInfo.orderNo)
      }
    }
  })

  useEffect(() => {
    //进入此页面后10秒后才开始轮询查询支付状态
    const delayTaskId = setTimeout(() => {
      runRefreshPayRecord();    //开始轮询
    }, 10000);
    return () => {
      clearTimeout(delayTaskId)
      cancelRefreshPayRecord(); //停止轮询
    }
  }, []);

  useStompSubscription(DEFAULT_WS_TOPICS.USER_TOPIC,
    (msg) => {
      if (msg.extras?.orderNo === pendingPayInfo.orderNo) {
        onDebouncePaymentSuccess(pendingPayInfo.orderNo)
      }
    },
    ["PAY_NOTIFY"]
  )


  return (
    <div className={"ppinfo-container"}>
      <div className={"oci-content"}>
        <div className={"oci-content-title"}><FormattedMessage id="mall.SubscriptionPayInfo"/></div>
        <Divider/>
        <div className={"ppinfo-subject"}>
          {pendingPayInfo.subject}
        </div>
        <Divider/>
        <div className={"oci-desc-item"}>
          <span className={"oci-desc-item-label"}><FormattedMessage id="mall.SubscriptionPayOrderNumber"/>:</span>
          <span className={"oci-desc-item-content"}>{pendingPayInfo.orderNo}</span>
        </div>
        <div className={"ppinfo-amount"}>
          <div className={"oci-desc-item"}>
            <span className={"oci-desc-item-label"}><FormattedMessage id="mall.SubscriptionPayAmount"/>:</span>
            <span className={"oci-desc-item-content"}>￥{numeral(parseFloat(pendingPayInfo.totalAmount) / 100).format('0.00')}</span>
          </div>
        </div>
        <Divider/>
        <div className={"oci-qrcode-wrapper"}>
          <QRCode
            icon={pendingPayInfo.qrCodeIcon}
            iconSize={80}
            value={pendingPayInfo.qrCode}
            size={300}
          />
          <div className={"qrcode-tip"}>
            <div><FormattedMessage id="mall.SubscriptionPayCountdownHelp1" values={{payMethod: pendingPayInfo.paywayStr}}/></div>
            <div><FormattedMessage id="mall.SubscriptionPayCountdownHelp2" values={{countdown: `${Math.round(limlitPaymentTimeCountdown / 1000)}`}}/></div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MallOrderPendingPayinfo;
